package com.qsmx.qingqiuticket.app.delegate.back;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateInstallCleanBinding;
import com.qsmx.qingqiuticket.app.entity.BaseEntity;
import com.qsmx.qingqiuticket.app.entity.PackageListEntity;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.net.HttpUrl;

import java.lang.reflect.Type;

public class BackInstallAndCleanDelegate extends AtmosDelegate {

    private Dialog mInstallCleanDialog;
    private Dialog mWaringDialog;

    DelegateInstallCleanBinding mBinding;

    @Override
    public Object setLayout() {
        return R.layout.delegate_install_clean;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        mBinding = DelegateInstallCleanBinding.bind(rootView);
        mBinding.tvBack.setOnClickListener(v -> getSupportDelegate().pop());

        mBinding.tvPrintWaring1Ticket.setText("当前预警值：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_WARING_TICKET_NUM));
        mBinding.tvPrintWaring2Ticket.setText("当前预警值：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_WARING_TICKET_NUM));
        mBinding.tvPrintWaring3Ticket.setText("当前预警值：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_WARING_TICKET_NUM));

        mBinding.tvPrint1Ticket.setText("当前余票：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM));
        mBinding.tvPrint2Ticket.setText("当前余票：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM));
        mBinding.tvPrint3Ticket.setText("当前余票：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM));

        onClick();

    }

    private void onClick() {

        mBinding.tvPrintAdd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInstallCleanDialog("1", true,
                        AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM));
            }
        });

        mBinding.tvPrintClean1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInstallCleanDialog("1", false,
                        AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM));
            }
        });

        mBinding.tvSetPrintWaring1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWaringTicketDialog("1");
            }
        });

        mBinding.tvPrintAdd2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInstallCleanDialog("2", true,
                        AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM));
            }
        });

        mBinding.tvPrintClean2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInstallCleanDialog("2", false,
                        AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM));
            }
        });
        mBinding.tvSetPrintWaring2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWaringTicketDialog("2");
            }
        });

        mBinding.tvPrintAdd3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInstallCleanDialog("3", true,
                        AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM));
            }
        });

        mBinding.tvPrintClean3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInstallCleanDialog("3", false,
                        AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM));
            }
        });

        mBinding.tvSetPrintWaring3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWaringTicketDialog("3");
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void showWaringTicketDialog(String printNo) {

        if (mWaringDialog != null) {
            mWaringDialog.dismiss();
        } else {
            mWaringDialog = new Dialog(requireContext(), com.qsmx.core.R.style.dialog);
        }

        mWaringDialog.setCancelable(false);
        Window window = mWaringDialog.getWindow();
        window.setContentView(R.layout.dialog_waring_ticket);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        mWaringDialog.show();

        AppCompatTextView tvPrintNo = window.findViewById(R.id.tv_print_no);
        AppCompatEditText etWaringTicketNum = window.findViewById(R.id.et_waring_ticket_num);
        AppCompatTextView tvBack = window.findViewById(R.id.tv_back);
        AppCompatTextView tvSure = window.findViewById(R.id.tv_sure);

        tvPrintNo.setText("打印机-" + printNo);

        tvBack.setOnClickListener(v -> {
            if (mWaringDialog != null) {
                mWaringDialog.dismiss();
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (StringUtil.isEmpty(etWaringTicketNum.getText().toString())) {
                        DialogUtil.showCardErrorDialog(requireContext(), "预警值不能为空", "确定");
                        return;
                    }
                    if (StringUtil.IntegerValueOf(etWaringTicketNum.getText().toString(), 0) < 0) {
                        DialogUtil.showCardErrorDialog(requireContext(), "预警值不能小于0", "确定");
                        return;
                    }
                    if (mWaringDialog != null) {
                        mWaringDialog.dismiss();
                    }
                    if (printNo.equals("1")) {
                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_ONE_WARING_TICKET_NUM, etWaringTicketNum.getText().toString());
                        mBinding.tvPrintWaring1Ticket.setText("当前预警值：" + etWaringTicketNum.getText().toString());
                    } else if (printNo.equals("2")) {
                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_TWO_WARING_TICKET_NUM, etWaringTicketNum.getText().toString());
                        mBinding.tvPrintWaring2Ticket.setText("当前预警值：" + etWaringTicketNum.getText().toString());
                    } else if (printNo.equals("3")) {
                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_THREE_WARING_TICKET_NUM, etWaringTicketNum.getText().toString());
                        mBinding.tvPrintWaring3Ticket.setText("当前预警值：" + etWaringTicketNum.getText().toString());
                    }
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void showInstallCleanDialog(String printNo, boolean isInstall, String ticketNum) {

        if (mInstallCleanDialog != null) {
            mInstallCleanDialog.dismiss();
        } else {
            mInstallCleanDialog = new Dialog(requireContext(), com.qsmx.core.R.style.dialog);
        }

        mInstallCleanDialog.setCancelable(false);
        Window window = mInstallCleanDialog.getWindow();
        window.setContentView(R.layout.dialog_install_and_clean);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        mInstallCleanDialog.show();

        AppCompatTextView tvPrintNo = window.findViewById(R.id.tv_print_no);
        AppCompatTextView tvPrintInstallOrCleanTips = window.findViewById(R.id.tv_print_install_or_clean_tips);
        AppCompatEditText etTicketNum = window.findViewById(R.id.et_ticket_num);
        AppCompatTextView tvTicketNum = window.findViewById(R.id.tv_ticket_num);
        AppCompatTextView tvBack = window.findViewById(R.id.tv_back);
        AppCompatTextView tvSure = window.findViewById(R.id.tv_sure);

        if (isInstall) {
            tvPrintInstallOrCleanTips.setText("安装门票张数");
            etTicketNum.setHint("余票数+安装数<=500");
        } else {
            tvPrintInstallOrCleanTips.setText("回收门票张数");
            etTicketNum.setHint("余票数-回收数>=0");
        }

        tvPrintNo.setText("打印机-" + printNo);
        tvTicketNum.setText("当前余票数：" + ticketNum);

        tvBack.setOnClickListener(v -> {
            if (mInstallCleanDialog != null) {
                mInstallCleanDialog.dismiss();
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (isInstall) {

                        if (StringUtil.IntegerValueOf(etTicketNum.getText().toString(), 0) + StringUtil.IntegerValueOf(ticketNum, 0) <= 500) {
                            mInstallCleanDialog.dismiss();
                            SetTicketNum(printNo,
                                    ticketNum,
                                    etTicketNum.getText().toString(),
                                    true);
                        } else {
                            DialogUtil.showCardErrorDialog(requireContext(), "票总数不能大于500张", "确定");
                            etTicketNum.setText("");
                        }
                    } else {
                        if (StringUtil.IntegerValueOf(ticketNum, 0) - StringUtil.IntegerValueOf(etTicketNum.getText().toString(), 0) >= 0) {
                            mInstallCleanDialog.dismiss();
                            SetTicketNum(printNo,
                                    ticketNum,
                                    etTicketNum.getText().toString(),
                                    false);
                        } else {
                            DialogUtil.showCardErrorDialog(requireContext(), "票总数不能小于0张", "确定");
                            etTicketNum.setText("");
                        }
                    }
                }
            }
        });
    }

    private void SetTicketNum(String printId, String beforeNum, String changeNum, boolean isInstall) {
        DialogUtil.showLoadingDialog(requireContext(), "正在设置...");
        long orderNoTime = System.currentTimeMillis();
        String serialNo = "LS" + AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM) + orderNoTime + StringUtil.getRandomNumString(6);

        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("printId", printId);
        params.put("serialNo", serialNo);
        if (StringUtil.isNotEmpty(beforeNum)) {
            params.put("beforeNum", beforeNum);
        } else {
            params.put("beforeNum", "0");
        }
        params.put("changeNum", changeNum);
        if (isInstall) {
            params.put("changeType", "2");
        } else {
            params.put("changeType", "3");
        }

        HttpHelper.RestClientPostRaw(params, HttpUrl.PRINT_RECORD,
                new ISuccess() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<BaseEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            BaseEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals("200")) {
                                DialogUtil.showCardErrorDialog(requireContext(), "设置成功", "确定");
                                if (isInstall) {
                                    if (printId.equals("1")) {
                                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM, StringUtil.IntegerValueOf(beforeNum, 0) + StringUtil.IntegerValueOf(changeNum, 0) + "");
                                    } else if (printId.equals("2")) {
                                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM, StringUtil.IntegerValueOf(beforeNum, 0) + StringUtil.IntegerValueOf(changeNum, 0) + "");
                                    } else if (printId.equals("3")) {
                                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM, StringUtil.IntegerValueOf(beforeNum, 0) + StringUtil.IntegerValueOf(changeNum, 0) + "");
                                    }
                                } else {
                                    if (printId.equals("1")) {
                                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM, StringUtil.IntegerValueOf(beforeNum, 0) - StringUtil.IntegerValueOf(changeNum, 0) + "");
                                    } else if (printId.equals("2")) {
                                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM, StringUtil.IntegerValueOf(beforeNum, 0) - StringUtil.IntegerValueOf(changeNum, 0) + "");
                                    } else if (printId.equals("3")) {
                                        AtmosPreference.addCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM, StringUtil.IntegerValueOf(beforeNum, 0) - StringUtil.IntegerValueOf(changeNum, 0) + "");
                                    }
                                }
                                if (mInstallCleanDialog != null) {
                                    mInstallCleanDialog.dismiss();
                                }
                                mBinding.tvPrint1Ticket.setText("当前余票：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM));
                                mBinding.tvPrint2Ticket.setText("当前余票：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM));
                                mBinding.tvPrint3Ticket.setText("当前余票：" + AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM));

                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(requireContext(), e.getMessage(), "确定");
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                    }
                });
    }
}
